const http = require("http");
const WebSocket = require("ws");

const initWS = (app) => {
  const server = http.createServer(app);
  const wss = new WebSocket.Server({ server });

  wss.on("connection", (ws) => {
    console.log("Client connected");

    ws.on("error", console.error);

    ws.on("open", function open() {
      ws.send("something");
    });

    ws.on("message", (message) => {
      console.log(`Received message: ${message}`);
      ws.send("Received: " + message);
    });

    ws.on("close", () => {
      console.log("Client disconnected");
    });
  });

  return server;
};

module.exports = initWS;
